/**
 * 
 */
package org.json.simple;

import java.io.IOException;
import java.io.Writer;
import java.util.List;
import java.util.Map;

/**
 * @author Roger Xu<roger.xu.2007@gmail.com>
 */
public class JSONValue {

    /**
     * Encode an object into JSON text and write it to out.
     * <p>
     * If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware.
     * <p>
     * DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or
     * List) with "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or
     * JSONArray.writeJSONString(List, Writer) instead.
     * 
     * @see org.json.simple.JSONObject#writeJSONString(Map, Writer, boolean)
     * @see org.json.simple.JSONArray#writeJSONString(List, Writer, boolean)
     * 
     * @param value
     *            The object.
     * @param out
     *            The Writer object.
     * @param isPretty
     *            true if output in a pretty style format
     */
    @SuppressWarnings("unchecked")
    public static void writeJSONString(final Object value, final Writer out, final boolean isPretty) throws IOException {
        if (value == null) {
            out.append("null");
            return;
        }

        if (value instanceof String) {
            out.append('\"');
            out.append(escape((String) value));
            out.append('\"');
            return;
        }

        if (value instanceof Number) {
            if (value instanceof Double) {
                if (((Double) value).isInfinite() || ((Double) value).isNaN()) {
                    out.append("null");
                    return;
                }
            }

            if (value instanceof Float) {
                if (((Float) value).isInfinite() || ((Float) value).isNaN()) {
                    out.append("null");
                    return;
                }
            }

            out.append(value.toString());
            return;
        }

        if (value instanceof Boolean) {
            out.append(value.toString());
            return;
        }

        if (value instanceof Map<?, ?>) {
            JSONObject.writeJSONString((Map<String, Object>) value, out, isPretty);
            return;
        }

        if (value instanceof List<?>) {
            JSONArray.writeJSONString((List<Object>) value, out, isPretty);
            return;
        }

        // if((value instanceof JSONStreamAware)){
        // ((JSONStreamAware)value).writeJSONString(writer);
        // return;
        // }

        if ((value instanceof JSONAware)) {
            out.append(((JSONAware) value).toJSONString(isPretty));
            return;
        }

        out.append(value.toString());
    }

    /**
     * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
     * 
     * @param str
     * @return
     */
    public static String escape(final String str) {
        if (str == null) {
            return null;
        }
        StringBuilder sb = new StringBuilder();
        escape(str, sb);

        return sb.toString();
    }

    /**
     * @param str
     *            Must not be null.
     * @param sb
     *            StringBuilder
     */
    static void escape(final String str, final StringBuilder sb) {
        for (int i = 0; i < str.length(); i++) {
            char ch = str.charAt(i);
            switch (ch) {
            case '"':
                sb.append("\\\"");
                break;
            case '\\':
                sb.append("\\\\");
                break;
            case '\b':
                sb.append("\\b");
                break;
            case '\f':
                sb.append("\\f");
                break;
            case '\n':
                sb.append("\\n");
                break;
            case '\r':
                sb.append("\\r");
                break;
            case '\t':
                sb.append("\\t");
                break;
            case '/':
                sb.append("\\/");
                break;
            default:
                // Reference: http://www.unicode.org/versions/Unicode5.1.0/
                if ((ch >= '\u0000' && ch <= '\u001F') || (ch >= '\u007F' && ch <= '\u009F')
                        || (ch >= '\u2000' && ch <= '\u20FF')) {
                    String ss = Integer.toHexString(ch);
                    sb.append("\\u");
                    for (int k = 0; k < 4 - ss.length(); k++) {
                        sb.append('0');
                    }
                    sb.append(ss.toUpperCase());
                } else {
                    sb.append(ch);
                }
            }
        }// for
    }

}
